﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Sharp.Infrastructure.Search
{
    public partial class QuerySupport<TEntity>
    {
        private BinaryExpression GetSection(Type propertyType, string searchValue, bool start, string searchFor)
        {
            if (searchValue.IsNullOrEmpty()) return null;

            if (propertyType==typeof(DateTime) || propertyType == typeof(DateTime?))
            {
                return GetDateTime(propertyType, searchValue, start, searchFor);
            }
            else
            {
                return GetNormal(propertyType, searchValue, start, searchFor);
            }
        }

        private BinaryExpression GetDateTime(Type propertyType, string searchValue, bool start, string searchFor)
        {
            DateTime dt = (DateTime)ConvertHelper.ChangeType(searchValue, propertyType);
            if (start)
            {
                ConstantExpression begin = Expression.Constant(dt, propertyType);
                var beginThan = Expression.GreaterThanOrEqual(GetPropertyExpression(null, Parameter, searchFor), begin);

                return beginThan;
            }
            else
            {
                dt = dt.AddDays(1);
                ConstantExpression end = Expression.Constant(dt, propertyType);
                var endThan = Expression.LessThan(GetPropertyExpression(null, Parameter, searchFor), end);

                return endThan;
            }

        }

        private BinaryExpression GetNormal(Type propertyType, string searchValue, bool start, string searchFor)
        {
            if (start)
            {
                ConstantExpression begin = Expression.Constant(ConvertHelper.ChangeType(searchValue, propertyType), propertyType);
                return Expression.GreaterThanOrEqual(GetPropertyExpression(null, Parameter, searchFor), begin);
            }
            else
            {
                ConstantExpression end = Expression.Constant(ConvertHelper.ChangeType(searchValue, propertyType), propertyType);
                return Expression.LessThanOrEqual(GetPropertyExpression(null, Parameter, searchFor), end);
            }
        }
    }
}